# -*- coding: utf-8 -*-
# @Author  : longbhu
# @Time    : 2025/7/21 14:40
# @Function:
from flask import request, jsonify
from routes import app
from services.homepage_service import homepage_service


@app.route("/homepage", methods=['GET'])
def get_homepage_data():
    year = request.args.get('year')
    district = request.args.get('district')

    if not year or not district:
        return jsonify({'error': 'Missing year or district parameter'}), 400

    try:
        year = int(year)
    except ValueError:
        return jsonify({'error': 'Invalid year format'}), 400

    record_bar01 = homepage_service.get_homepage_data_bar01(year=year, district=district)
    record_pie01 = homepage_service.get_homepage_data_pie01(year=year, district=district)
    record_bar02 = homepage_service.get_homepage_data_bar02(year=year, district=district)
    record_bar03 = homepage_service.get_homepage_data_bar03(year=year, district=district)
    record_pie02 = homepage_service.get_homepage_data_pie02(year=year, district=district)
    record_form01 = homepage_service.get_homepage_data_form01(year=year, district=district)

    if record_bar01 and record_pie01:
        result = {
            'bar01': record_bar01,
            'pie01': record_pie01,
            'bar02': record_bar02,
            'bar03': record_bar03,
            'pie02': record_pie02,
            'form01': record_form01,
        }

        return jsonify(result), 200
    else:
        return jsonify({'error': 'Not found'}), 404


@app.route("/homepageMap", methods=['GET'])
def get_homepageMap_data():
    year = request.args.get('year')
    district = request.args.get('district')

    if not year or not district:
        return jsonify({'error': 'Missing year or district parameter'}), 400

    try:
        year = int(year)
    except ValueError:
        return jsonify({'error': 'Invalid year format'}), 400

    record_bar01 = homepage_service.get_homepage_data_bar01(year=year, district=district)
    if record_bar01:
        result = {
            'bar01': record_bar01,
        }
        return jsonify(result), 200
    else:
        return jsonify({'error': 'Not found'}), 404


@app.route("/vepPage", methods=['GET'])
def get_vepPage_data():
    year = request.args.get('year')
    district = request.args.get('district')

    if not year or not district:
        return jsonify({'error': 'Missing year or district parameter'}), 400

    try:
        year = int(year)
    except ValueError:
        return jsonify({'error': 'Invalid year format'}), 400

    record_form02 = homepage_service.get_homepage_data_form02(year=year, district=district)

    if record_form02 :
        return record_form02, 200
    else:
        return jsonify({'error': 'Not found'}), 404

